<template>
	<view>

		<!-- <camera device-position="back" mode="scanCode" bindscancode="scancode" flash="off" binderror="error" style="width: 100%; height: 300px;"></camera>
		<button type="primary" @click="takePhoto">拍照</button>
		<view>预览</view>
		<image mode="widthFix" :src="src"></image> -->
		<van-steps :steps="steps" :active="active" />
		<view class="" v-if="active==1">
			请把手机直接靠近新的卡片进行添加
		</view>
		<van-button v-if="active == 0" @click="nfcEnvironment">环境监测</van-button>
		<!-- <van-button v-if="active==1" @click="nfcStart">贴卡</van-button> -->
		<view class="" v-if="active==3">
			<van-button  @click="nfcEnvironment">再次添加卡片</van-button>
		</view>
		<view class="" v-if="active==2">
			<van-button  @click="nfcEnvironment">再次添加卡片</van-button>
		</view>
		
		<!-- 创建群组 -->
		<van-dialog use-slot title="请输入卡片信息" :show="show" show-cancel-button @confirm="onConfirm" @cancel="onCancel">
			<van-cell-group>
				<van-field label="卡片id" :value="aid" disabled maxlength="20"
					custom-style="border:2rpx solid #969799;width:95%;margin:auto;border-radius:10rpx;" />
				<view class="" style="height: 5rpx;width: ;">
					
				</view>
				<van-field label="卡片名称" :value="value" placeholder="限20个字" @change="onChange" maxlength="20"
					custom-style="margin-top:10rpx;border:2rpx solid #969799;width:95%;margin:auto;border-radius:10rpx;" />
			</van-cell-group>
		</van-dialog>
		<!-- 轻提示 -->
		<van-toast id="van-toast" />
	</view>
</template>

<script>
	import wrap from '@/components/wrap';
	import Dialog from '../../wxcomponents/vant/dialog/dialog';
	import Toast from '../../wxcomponents/vant/toast/toast';
	export default {
		data() {
			return {
				src: null,
				show:false,
				value:"",
				aid:"",
				steps: [{
						text: '步骤一',
						desc: '环境监测',
					},
					{
						text: '步骤二',
						desc: '检测卡片',
					},
					{
						text: '步骤三',
						desc: '录入信息',
					},
					{
						text: '步骤四',
						desc: '上传成功',
					},
				],
				active: 0
			}
		},
		methods: {
			//伪双向绑定
			onChange(event){
				this.value = event.detail;
			},
			onConfirm(){
				uni.request({
					url: this.apiurl + '/label/label',
					method:"POST",
					data: {
						labelNum:this.aid,
						title:this.value
					},
					header: {
						'Authorization': uni.getStorageSync("token")
					},
					success: (res) => {
						console.log(res.data);
						if(res.data.status == '1'){
							Toast.success('录入成功');
							this.active = 3;
						}else{
							Toast.fail(res.data.message)
							uni.showModal({
							    title: '提示',
							    content: res.data,
							    success: function (res) {
							        if (res.confirm) {
							            console.log('用户点击确定');
							        } else if (res.cancel) {
							            console.log('用户点击取消');
							        }
							    }
							});
						}
						
					}
				});
				
				this.show = false;
			},
			onCancel(){
				this.show = false
			},
			//重写nfc接口调用
			//检测nfc环境
			nfcEnvironment(){
				this.active = 0
				//1.调用适配器
				const NFCAdapter = wx.getNFCAdapter();
				//2.监听贴卡
				NFCAdapter.startDiscovery({
					success:res=>{
						console.log('成功'+res)
						Toast.success('成功文案');
						this.active = 1;
						this.nfcStart();
					},fail:err=>{
						console.log(err)
						if(err.errCode==13001){
							//系统nfc开关未打开
							Toast.fail('系统nfc开关未打开');
						}else if(err.errCode == 13000){
							//设备不支持
							Toast.fail('设备不支持');
						}else if(err.errCode == 13021){
							this.active = 1;
							this.nfcStart();
						}else{
							Toast.fail(err.errMsg);
							
						}
					}
				})
				// //3.结束监听
				// NFCAdapter.stopDiscovery({
				// 	success:res=>{
				// 		console.log(res)
						
				// 	},fail:err=>{
				// 		console.log(err)
				// 	}
				// })
			},
			//贴卡收集信息
			nfcStart(){
				console.log("启动监听")
				//字符转义
				/**
				 * 字节对象转字符串
				 * @param {Object} arr
				 */
				const byteToString = function(arr) {
					if (typeof arr === 'string') {
						return arr;
					}
				
					var str = '',
						_arr = arr;
				
					for (var i = 0; i < _arr.length; i++) {
						var one = _arr[i].toString(2),
							v = one.match(/^1+?(?=0)/);
				
						if (v && one.length == 8) {
							var bytesLength = v[0].length;
				
							var store = _arr[i].toString(2).slice(7 - bytesLength);
				
							for (var st = 1; st < bytesLength; st++) {
								store += _arr[st + i].toString(2).slice(2);
							}
				
							str += String.fromCharCode(parseInt(store, 2));
				
							i += bytesLength - 1;
						} else {
							str += String.fromCharCode(_arr[i]);
						}
					}
					return str;
				};
				
				/**
				 * 字符串转字节
				 * @param {Object} str
				 */
				const string2ArrayBuffer = function(str) {
					// 首先将字符串转为16进制
					let val = '';
					for (let i = 0; i < str.length; i++) {
						if (val === '') {
							val = str.charCodeAt(i).toString(16);
						} else {
							val += ',' + str.charCodeAt(i).toString(16);
						}
					}
					// 将16进制转化为ArrayBuffer
					return new Uint8Array(
						val.match(/[\da-f]{2}/gi).map(function(h) {
							return parseInt(h, 16);
						})
					).buffer;
				};
				/**
				 * 格式化得到aid值
				 * @param {Object} buffer
				 */
				const ab2hex = function(buffer) {
					var hexArr = Array.prototype.map.call(
						new Uint8Array(buffer),
				
						function(bit) {
							return ('00' + bit.toString(16)).slice(-2);
						}
					);
					return hexArr.join('');
				};
				
				
				
				//1.调用适配器
				const NFCAdapter = wx.getNFCAdapter();
				//2.
				NFCAdapter.onDiscovered(res => {
					console.log("贴卡监听回调")
					console.log(res)
					let aid = parseInt(ab2hex(res.id), 16);
					console.log(aid);
					this.aid = aid;
					this.active = 2;
					this.show = true;
					NFCAdapter.stopDiscovery({
						success:res=>{
							console.log('成功结束'+res)
						},fail:err=>{
							console.log('异常结束'+err)
						}
					})
					// const Ndef = NFCAdapter.getNdef()
					//     使用NfcA实例进行读写
					//     调用NfcA.connect()和NFC卡片建立连接
					// Ndef.connect({
					// 	success: res1 => {
					// 		console.log("连接nfc卡片成功");
					// 		console.log(res1)
					// 		let aid = parseInt(ab2hex(res.id), 16);
					// 		console.log(aid);
					// 		console.log(this.show)
					// 		this.show = true;
					// 		console.log(this.show)
					// 		this.aid = aid;
					// 		this.active = 2;
							
					// 		//准备写入的数据
					// 		const records = [{
					// 			id: string2ArrayBuffer("1001"),
					// 			payload: string2ArrayBuffer("M304"),
					// 			type: string2ArrayBuffer("U"),
					// 			tnf: 1
					// 		}];
					// 		//调用NfcA.transceive(Object object)往NFC卡片写入apdu指令并接收卡片返回数据
					
					// 	},
					// 	fail: err => {
					// 		console.log("连接nfc卡片失败")
					// 		console.log(err)
					// 	},
					// 	complete: com => {
					// 		console.log(com)
							
					// 	}
					// })
					// Ndef.offNdefMessage(callback=>{
					// 	console.log(callback)
					// 	console.log("取消监听")
					// })
					
				});
				
				
				
				
			},
			
			//
			takePhoto: function() {
				wx.scanCode({
					success(res) {
						console.log(res)
					}
				})
			},
			error: function(e) {
				console.log(e.detail)
			},
			scancode: function(e) {
				console.log(e.detail)
				this.nfc
			},
			//nfc接口
			nfc: function() {

				/**
				 * 字节对象转字符串
				 * @param {Object} arr
				 */
				const byteToString = function(arr) {
					if (typeof arr === 'string') {
						return arr;
					}

					var str = '',
						_arr = arr;

					for (var i = 0; i < _arr.length; i++) {
						var one = _arr[i].toString(2),
							v = one.match(/^1+?(?=0)/);

						if (v && one.length == 8) {
							var bytesLength = v[0].length;

							var store = _arr[i].toString(2).slice(7 - bytesLength);

							for (var st = 1; st < bytesLength; st++) {
								store += _arr[st + i].toString(2).slice(2);
							}

							str += String.fromCharCode(parseInt(store, 2));

							i += bytesLength - 1;
						} else {
							str += String.fromCharCode(_arr[i]);
						}
					}
					return str;
				};

				/**
				 * 字符串转字节
				 * @param {Object} str
				 */
				const string2ArrayBuffer = function(str) {
					// 首先将字符串转为16进制
					let val = '';
					for (let i = 0; i < str.length; i++) {
						if (val === '') {
							val = str.charCodeAt(i).toString(16);
						} else {
							val += ',' + str.charCodeAt(i).toString(16);
						}
					}
					// 将16进制转化为ArrayBuffer
					return new Uint8Array(
						val.match(/[\da-f]{2}/gi).map(function(h) {
							return parseInt(h, 16);
						})
					).buffer;
				};
				/**
				 * 格式化得到aid值
				 * @param {Object} buffer
				 */
				const ab2hex = function(buffer) {
					var hexArr = Array.prototype.map.call(
						new Uint8Array(buffer),

						function(bit) {
							return ('00' + bit.toString(16)).slice(-2);
						}
					);
					return hexArr.join('');
				};

				//获取NFCAAdapter实例
				const NFCAdapter = wx.getNFCAdapter();
				//     通过NFCAdapter.getNfcA()获取NfcA实例
				const Ndef = NFCAdapter.getNdef()
				//     调用NFCAdapter.onDiscovered(function callback)注册贴卡监听回调
				// NFCAdapter.onDiscovered(res=>{
				//     console.log("注册监听回调")
				//     console.log(res);
				// })
				//     调用NFCAdapter.startDiscovery(Object object)开始监听贴卡
				NFCAdapter.startDiscovery({
					success: res => {
						console.log("监听贴卡成功")
						console.log(res)
						uni.showLoading({
							title: '请贴近nfc卡片'
						});
					},
					fail: err => {
						console.log("监听贴卡失败")
						console.log(err)
						uni.showToast({
							icon: "error",
							title: '本机不支持nfc签到',
							duration: 2000
						});
					}
				})
				//     贴卡，onDiscovered回调
				NFCAdapter.onDiscovered(res => {
					console.log("贴卡监听回调")
					console.log(res)
					//     使用NfcA实例进行读写
					//     调用NfcA.connect()和NFC卡片建立连接
					Ndef.connect({
						success: res => {
							console.log("连接nfc卡片成功");
							console.log(res)
							let aid = parseInt(ab2hex(callback.id), 16);
							console.log(aid);
							// const records = [{
							// 	id: string2ArrayBuffer("1001"),
							// 	payload: string2ArrayBuffer("M304"),
							// 	type: string2ArrayBuffer("U"),
							// 	tnf: 1
							// }];
							//调用NfcA.transceive(Object object)往NFC卡片写入apdu指令并接收卡片返回数据
							// Ndef.writeNdefMessage({
							// 	// uris:string2ArrayBuffer("my.531party.cn"),
							// 	records: records,
							// 	success: res => {
							// 		console.log("写入成功")
							// 		console.log(res)
							// 	},
							// 	fail: err => {

							// 		console.log("写入失败")
							// 		console.log(string2ArrayBuffer("1001"))
							// 		console.log(err)
							// 	}
							// })
						},
						fail: err => {
							console.log("连接nfc卡片失败")
							console.log(err)
						}
					})
				})
				//     根据onDiscovered回调res对象的techs字段匹配到卡片支持NFC-A标准


				//     调用NfcA.transceive(Object object)往NFC卡片写入apdu指令并接收卡片返回数据
				//     读写完毕，调用NfcA.close()断开连接
				// NFCA.close({
				//     success:res=>{
				//         console.log("断开nfc卡片成功");
				//         console.log(res)
				//     },
				//     fail:err=>{
				//         console.log("断开nfc卡片失败")
				//         console.log(err)
				//     }
				// })
				//     调用NFCAdapter.stopDiscovery(Object object)结束监听贴卡
				// NFCAdapter.startDiscovery({
				//     success:res=>{
				//         console.log("结束监听成功");
				//         console.log(res)
				//     },
				//     fail:err=>{
				//         console.log("结束监听失败");
				//         console.log(err)
				//     }
				// })



			},
		},
		onLoad() {
			//查询登陆状态
			this.checkLogin();
			
			this.nfcEnvironment()
		},onShow() {
			this.show = false;
		}
	}
</script>

<style>
page > view > van-dialog > van-popup > view > van-cell-group > view > van-field:nth-child(2) > van-cell{
	margin-top: 10rpx;
}

</style>
